<?php

/**
 * @file
 * Extract an attribute value from a tag.
 */

$plugin = array(
  'form' => 'feeds_tamper_ccloud_extract_tag_attribute_form',
  'callback' => 'feeds_tamper_ccloud_extract_tag_attribute_callback',
  'name' => 'CCloud: Extract tag attribute',
  'multi' => 'loop',
  'category' => 'HTML',
);

function feeds_tamper_ccloud_extract_tag_attribute_form($importer, $element_key, $settings) {
  $form = array();

  $form['tag'] = array(
    '#type' => 'textfield',
    '#title' => t('Tag'),
    '#required' => TRUE,
    '#description' => t('Such as: img'),
    '#default_value' => isset($settings['tag']) ? $settings['tag'] : '',
  );

  $form['attribute'] = array(
    '#type' => 'textfield',
    '#title' => t('Attribute'),
    '#required' => TRUE,
    '#description' => t('Such as: src'),
    '#default_value' => isset($settings['attribute']) ? $settings['attribute'] : '',
  );

  return $form;
}

function feeds_tamper_ccloud_extract_tag_attribute_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  $tag = $settings['tag'];
  $attribute = $settings['attribute'];

  if (preg_match('/<' . $tag . '[^>]+>/i', $field, $tag_match)) {
    if (preg_match('/(' . $attribute . ')="([^"]*)"/i', $tag_match[0], $attribute_match)) {
      $field = $attribute_match[2];
    }
  }
}